#!/bin/bash

configfile=$1
oplpath=$2

from="multisimgen.support@tcl.com"
to="raffi.semerciyan@jrdcom.com"
subject="Multisimgen >check_com_ref.sh< notification"
tmp="/tmp/"
tmp1="/tmp/check_com_ref1"
tmp2="/tmp/check_com_ref2"

print_usage()
{
   echo "Usage: $0 <configfile> <oplpath>"
   echo "Check if the Commercial Reference exists in FTP1.CFG."
   echo "If not, send an email with the unknown Reference."
}

if [ "x$oplpath" == "x" ]; then
   echo "[ERROR] All arguments not available."
   print_usage
   exit 1
fi

find $oplpath -maxdepth 1 -name "*.000" -exec head -1 {} \; | sed s/\ //g | awk -F ";" '{print $5";"$3}'>/tmp/opl

if [ ! -s "/tmp/opl" ];then
    #file is empty
    exit 1
fi

#echo "not empty"

if [ -f $tmp1 ]; then
    rm $tmp1
fi

if [ -f $tmp2 ]; then
    rm $tmp2
fi

touch $tmp1 $tmp2
if [ ! -f $tmp1 ]; then
    exit 1
fi

if [ ! -f $tmp2 ]; then
    exit 1
fi

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Error in uut database.">>$tmp1

for i in `cat /tmp/opl`
  do

  ref=`echo $i | perl -e 'while (<STDIN>) { \$_=~s/([^\-]+\-.).(.+)/\$1\\\[\\\X\\\=\\\*\\\]\$2/; print;}' | awk -F ";" '{print $1}'`
  pt=`echo $i | awk -F ";" '{print $2}'`

  line=`cat $configfile | grep $ref | grep $pt`
  
  if [ $? -ne 0 ]; then
      #echo "$i    ...   Unknown"
      refcom=`echo $i | awk -F ";" '{print $1}'`
      #lockfile=$tmp$refcom"_"$pt
      lockfile=`echo $refcom$pt | md5sum | awk -F " " '{print $1}'`
      #echo $lockfile

      if [ ! -f $tmp$lockfile ];then
	  touch $tmp$lockfile
	  echo "REFCOM = "\"$refcom\"" PT = "\"$pt\">>$tmp2
	  continue
      fi
  fi
  
  #echo "$line"
  
done

if [ ! -s $tmp2 ];then
    #file is empty
    exit 1
fi

cat $tmp2 >> $tmp1

/data/scripts/sendmail.pl -f "$from" -t "$to" -s "$subject" $tmp1
rm $tmp1
rm $tmp2
